<template>
  <el-container>
    <el-header>
      <el-input v-model="filterText" placeholder="Filter keyword" style="padding: 10px 0;"/>
    </el-header>
    <el-main class="scroll">
      <el-tree
          ref="tree2"
          :data="data2"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          default-expand-all
      />
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: 'list',
  data() {
    return {
      filterText: '',
      data2: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    }
  },
  beforeMount() {
    this.getList();
  },
  methods: {
    getList() {
      this.$api.api_edu.subjectList().then(res => {
        if (res.success) {
          let data = res.data && res.data.data || []
          let tree = this.data2Tree(data)
          this.data2 = tree;
        }
      })
    },
    data2Tree(data) {
      let pid = data.filter(o => o.parentId === '0').map(o => o.id);
      let parent = [];
      let other = [];
      data.forEach(item => {
        if (pid.includes(item.parentId)) {
          other.push(item)
        } else {
          parent.push(item)
        }
      });

      let deepin = (parent, other) => {
        let map = {}
        parent.forEach(o => map[o.id] = o);
        let l1 = [];
        let l2 = [];
        other.forEach(item => {
          let par = map[item.parentId];
          if (par) {
            let ch = par.children || [];
            ch.push(item)
            l1.push(item);
            par.children = ch;
          } else {
            l2.push(item)
          }
        })
        if (l2.length > 0 && l1.length > 0) deepin(l1, l2)
      }
      deepin(parent, other);
      return parent;
    },
    filterNode(value, data) {
      if (!value) return true
      return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1
    }
  }
}
</script>

<style>

</style>
